<template>
  <div class="consult-form">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="120px">
      <!-- 长者基本信息 -->
      <div class="form-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="长者姓名" prop="elderName" required>
              <el-input v-model="formData.elderName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="gender" required>
              <el-select v-model="formData.gender" placeholder="请选择" class="full-width">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年龄" prop="age">
              <el-input v-model.number="formData.age" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="户籍地址">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-select
                v-model="formData.registeredProvince"
                placeholder="省、直辖市"
                class="full-width"
              >
                <el-option label="重庆市" value="重庆市" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="formData.registeredCity" placeholder="市" class="full-width">
                <el-option label="重庆市" value="重庆市" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select
                v-model="formData.registeredDistrict"
                placeholder="区、县"
                class="full-width"
              >
                <el-option label="渝北区" value="渝北区" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-input v-model="formData.registeredDetail" placeholder="详细地址" />
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="家庭住址">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-select
                v-model="formData.homeProvince"
                placeholder="省、直辖市"
                class="full-width"
              >
                <el-option label="重庆市" value="重庆市" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="formData.homeCity" placeholder="市" class="full-width">
                <el-option label="重庆市" value="重庆市" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="formData.homeDistrict" placeholder="区、县" class="full-width">
                <el-option label="渝北区" value="渝北区" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-input v-model="formData.homeDetail" placeholder="详细地址" />
            </el-col>
          </el-row>
        </el-form-item>
      </div>

      <!-- 咨询人信息 -->
      <div class="form-section">
        <h3>咨询人信息</h3>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="咨询人姓名" prop="consultantName" required>
              <el-input v-model="formData.consultantName" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="consultantGender">
              <el-select
                v-model="formData.consultantGender"
                placeholder="请选择"
                class="full-width"
              >
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="与长者关系" prop="relationship">
              <el-select v-model="formData.relationship" placeholder="请选择" class="full-width">
                <el-option label="子女" value="子女" />
                <el-option label="配偶" value="配偶" />
                <el-option label="其他亲属" value="其他亲属" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话" prop="consultantPhone" required>
              <el-input v-model="formData.consultantPhone" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 咨询情况 -->
      <div class="form-section">
        <h3>咨询情况</h3>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="咨询方式" prop="consultMethod">
              <el-select v-model="formData.consultMethod" placeholder="请选择" class="full-width">
                <el-option label="电话咨询" value="电话咨询" />
                <el-option label="到访咨询" value="到访咨询" />
                <el-option label="网络咨询" value="网络咨询" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="信息获取来源" prop="infoSource">
              <el-select v-model="formData.infoSource" placeholder="请选择" class="full-width">
                <el-option label="网络搜索" value="网络搜索" />
                <el-option label="朋友推荐" value="朋友推荐" />
                <el-option label="广告宣传" value="广告宣传" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="接待时间" prop="receptionTime">
              <el-date-picker
                v-model="formData.receptionTime"
                type="datetime"
                placeholder="选择日期时间"
                class="full-width"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="接待人" prop="receptionist">
              <el-input v-model="formData.receptionist" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="情况说明" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请填写咨询相关内容"
          />
        </el-form-item>
      </div>

      <!-- 跟进情况 -->
      <div class="form-section">
        <h3>跟进情况</h3>
        <el-form-item label="咨询程度" prop="intentLevel" required>
          <el-radio-group v-model="formData.intentLevel" class="radio-group">
            <el-radio label="仅咨询">仅咨询</el-radio>
            <el-radio label="一般入住意向">一般入住意向</el-radio>
            <el-radio label="强烈入住意向">强烈入住意向</el-radio>
            <el-radio label="已申请入住">已申请入住</el-radio>
            <el-radio label="无入住意向">无入住意向</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="意向说明" prop="intentDescription">
          <el-input
            v-model="formData.intentDescription"
            type="textarea"
            :rows="3"
            placeholder="请面谈具体的入住时间和需求、护理需求、护理要求、特殊要求等"
          />
        </el-form-item>

        <el-form-item label="跟进进度" prop="followStatus">
          <el-radio-group v-model="formData.followStatus" class="radio-group">
            <el-radio label="跟进中">跟进中，无需跟进</el-radio>
            <el-radio label="结束">结束，无需跟进</el-radio>
            <el-radio label="完成">完成，已转入住</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="下次跟进日期" prop="nextFollowDate">
              <el-date-picker
                v-model="formData.nextFollowDate"
                type="date"
                placeholder="选择日期"
                class="full-width"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="跟进人" prop="followPerson">
              <el-select v-model="formData.followPerson" placeholder="请选择" class="full-width">
                <el-option label="王接待" value="王接待" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <div class="form-actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { addRecord, getRecordById, updateRecord } from '@/services/consult'
import type { ConsultRecord } from '@/types/consult'

const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance>()
const isEdit = ref(false)

const formData = reactive({
  elderName: '',
  gender: '',
  age: '',
  phone: '',
  registeredProvince: '',
  registeredCity: '',
  registeredDistrict: '',
  registeredDetail: '',
  homeProvince: '',
  homeCity: '',
  homeDistrict: '',
  homeDetail: '',
  consultantName: '',
  consultantGender: '',
  relationship: '',
  consultantPhone: '',
  consultMethod: '',
  infoSource: '',
  receptionTime: '',
  receptionist: '',
  description: '',
  intentLevel: '',
  intentDescription: '',
  followStatus: '跟进中',
  nextFollowDate: '',
  followPerson: '',
  firstConsultTime: '',
  firstReception: '',
  status: '跟进中',
  followNote: '',
})

const rules = reactive({
  elderName: [{ required: true, message: '请输入长者姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  consultantName: [{ required: true, message: '请输入咨询人姓名', trigger: 'blur' }],
  consultantPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  intentLevel: [{ required: true, message: '请选择咨询程度', trigger: 'change' }],
})

// 加载编辑数据
const loadEditData = () => {
  const id = route.params.id as string
  if (id) {
    isEdit.value = true
    const record = getRecordById(id)
    if (record) {
      Object.assign(formData, record)
    } else {
      ElMessage.error('未找到相关记录')
      router.push('/')
    }
  } else {
    // 新增时设置默认值
    formData.firstConsultTime = new Date().toISOString().split('T')[0]
    formData.receptionTime = new Date().toISOString().split('T')[0]
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate((valid) => {
    if (valid) {
      try {
        if (isEdit.value) {
          const id = route.params.id as string
          const success = updateRecord({
            ...formData,
            id,
            age: Number(formData.age),
          })
          if (success) {
            ElMessage.success('更新成功')
            router.push('/')
          } else {
            ElMessage.error('更新失败')
          }
        } else {
          const {
            elderName,
            gender,
            age,
            phone,
            consultantName,
            relationship,
            intentLevel,
            intentDescription,
            status,
            nextFollowDate,
            followPerson,
            followNote,
            firstConsultTime,
            firstReception,
          } = formData

          const record = addRecord({
            elderName,
            gender,
            age: Number(age),
            phone,
            consultantName,
            relationship,
            intentLevel,
            intentDescription,
            status,
            nextFollowDate,
            followPerson,
            followNote,
            firstConsultTime,
            firstReception,
          })

          if (record) {
            ElMessage.success('添加成功')
            router.push('/')
          } else {
            ElMessage.error('添加失败')
          }
        }
      } catch (err) {
        console.error(err)
        ElMessage.error('操作失败')
      }
    }
  })
}

const handleCancel = () => {
  router.push('/')
}

onMounted(() => {
  loadEditData()
})
</script>

<style scoped>
.consult-form {
  padding: 20px;
  background-color: #fff;
  min-width: 1000px;
}

.form-section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.form-section:last-child {
  border-bottom: none;
}

.form-section h3 {
  margin: 0 0 15px 0;
  padding: 8px 0;
  font-size: 14px;
  font-weight: bold;
  color: #606266;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: normal;
  color: #606266;
  padding-right: 20px;
}

:deep(.el-input),
:deep(.el-select),
:deep(.el-date-picker),
.full-width {
  width: 100%;
}

:deep(.radio-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

:deep(.el-radio) {
  margin-right: 0;
  white-space: nowrap;
}

:deep(.el-radio__label) {
  font-size: 13px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

:deep(.el-form-item.is-required > .el-form-item__label::before) {
  margin-right: 2px;
}

/* 调整栅格间距 */
:deep(.el-row) {
  margin-bottom: -18px;
}

:deep(.el-select-dropdown__item) {
  font-size: 13px;
}

:deep(.el-input__inner) {
  font-size: 13px;
}
</style>
